package com.eorchis.util;

import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.stream.XMLStreamWriter;

import org.apache.log4j.Logger;

public class BeanToXMLUtils {
	private static final Logger logger = Logger.getLogger(BeanToXMLUtils.class);

	public static final String toXMLString(final Object o) {
		if (o == null) {
			return null;
		}

		String xml = null;
		try {
			JAXBContext jc = JAXBContext.newInstance(o.getClass());
			Marshaller marshaller = jc.createMarshaller();

			boolean debugEnabled = logger.isDebugEnabled();
			if (debugEnabled) {
				marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
			}

			StringWriter sw = new StringWriter();

			XMLStreamWriter streamWriter = new XMLStreamWriterForCDATA(sw);

			marshaller.marshal(o, streamWriter);

			xml = sw.toString();

			logger.debug("Object is [" + o + "], xml is [" + xml + "]");
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

		return xml;
	}
}
